package com.zmytest.service.impl;

import com.zmytest.dto.ResponseDto;
import com.zmytest.dto.UserDto;
import com.zmytest.model.User;
import com.zmytest.repository.UserRepository;
import com.zmytest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * Created on 2018/12/19.
 *
 * @author zhangmingyu
 *
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public ResponseDto<User> create(UserDto userDto) {
        if (!ObjectUtils.isEmpty(userDto.getId())) {
            return ResponseDto.fail("user id must be null");
        }
        User result = userRepository.save(new User(userDto.getName(),userDto.getBirth(),userDto.getMail()));
        return ResponseDto.success(result);
    }

    @Override
    public ResponseDto<User> find(Long id) {
        User user = userRepository.findOne(id);
        return ResponseDto.success(user);
    }

    @Override
    public ResponseDto<User> update(UserDto userDto) {
        Long id = userDto.getId();
        if (ObjectUtils.isEmpty(id)) {
            return ResponseDto.fail("user id can not be null");
        }
        User user = userRepository.getOne(id);
        user.update(userDto);
        User result = userRepository.save(user);
        return ResponseDto.success(result);
    }

    @Override
    public ResponseDto<String> delete(Long id) {
        userRepository.delete(id);
        return ResponseDto.success("delete success");
    }
}
